package com.codechuan.didi_web.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 从HTTP头信息中取得token
        String token = request.getHeader("token");
        if (request.getRequestURI().equals("/account/login") || request.getRequestURI().equals("/account/start"))
            return true;
        // 实现token验证的逻辑
        return validateToken(token, response, request);
    }

    private boolean validateToken(String token, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String msg = "登录失效,请重新登录.";
        boolean flag = true;
        if(token == null)
            return true;
        String value = redisTemplate.opsForValue().get(token);
        if (value == null) {
            flag = false;
            response.setStatus(200);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            JSONObject data = new JSONObject();
            jsonObject.put("code", 401);
            jsonObject.put("message", msg);
            data.put("code", 401);
            data.put("message", msg);
            data.put("data", null);
            jsonObject.put("data", data);
            jsonObject.put("uri", request.getRequestURI());
            jsonObject.put("url", request.getRequestURL());
            writer.println(jsonObject);
            writer.flush();
            writer.close();
        }

        return flag;
    }
}